﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.ComponentModel;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Workflow;
using System.Workflow.ComponentModel.Compiler;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;
using System.Text.RegularExpressions;

namespace CrmContrib.Workflow.Activities.Utilities
{
    [CrmWorkflowActivity("Sanitize email message", "CrmContrib \\ Utilities")]
    public class SanitizeEmailMessageActivity : Activity
    {
        [CrmInput("EmailId")]
        [CrmReferenceTarget("email")]
        [ValidationOption(ValidationOption.Required)]
        public Lookup EmailId
        {
            get { return (Lookup)base.GetValue(EmailIdProperty); }
            set { base.SetValue(EmailIdProperty, value); }
        }

        public static readonly DependencyProperty EmailIdProperty = DependencyProperty.Register("EmailId", typeof(Lookup), typeof(SanitizeEmailMessageActivity));


        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            var contextService = executionContext.GetService<IContextService>();
            var workflowContext = contextService.Context;
            var crmService = workflowContext.CreateCrmService();

            email theEmail = (email)crmService.Retrieve("email", this.EmailId.Value, new AllColumns());
            if (theEmail != null)
            {
                SanitizedEmailMessage = StripHml(theEmail.description);
                SanitizedEmailMessage = SanitizedEmailMessage.Replace("v\\:* {behavior:url(#default#VML);}", "");
                SanitizedEmailMessage = SanitizedEmailMessage.Replace("o\\:* {behavior:url(#default#VML);}", "");
                SanitizedEmailMessage = SanitizedEmailMessage.Replace("w\\:* {behavior:url(#default#VML);}", "");
                SanitizedEmailMessage = SanitizedEmailMessage.Replace(".shape {behavior:url(#default#VML);}", "");
                SanitizedEmailMessage = SanitizedEmailMessage.Trim();

            }



            return base.Execute(executionContext);
        }

        public string StripHml(string message)
        {
            return Regex.Replace(message, "<.*?>", string.Empty); ;
        }

        [CrmOutput("SanitizedEmailMessage")]
        public String SanitizedEmailMessage
        {
            get { return (String)base.GetValue(SanitizedEmailMessageProperty); }
            set { base.SetValue(SanitizedEmailMessageProperty, value); }
        }

        public static readonly DependencyProperty SanitizedEmailMessageProperty = DependencyProperty.Register("SanitizedEmailMessage", typeof(String), typeof(SanitizeEmailMessageActivity));
    }
}
